<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/20 0020
 * Time: 8:53
 */
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Query;

class Querys extends Controller
{
    public function index()
    {
//        $name = input('post.name');
//        $encodeName = urlencode($name);
//        $url = "http://api.91cha.com/index?key=fa3ebdbc2dac4232add346c4b2171e56&kws=$encodeName";
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//        $result = curl_exec($ch);
//        $data = json_decode($result,true);
//        $value = $data['data'];
//            foreach ($value as $k=>$v)
//            {
//                echo $bai = $v['mobileindex'].PHP_EOL;
//                echo $so360 = $v['so360index'].PHP_EOL;
//                echo $so = round($v['mobileindex'] * 0.9) .PHP_EOL;
//                echo $sm = round($v['mobileindex'] * 0.7) .PHP_EOL;
//                echo $baiPc = round($v['mobileindex'] * 1.2);
//            }
//        halt($value);
//        curl_close($ch);

        //指数模式： 计算关键字价格
//        $price_mode = config('site.price_mode');
//        if($price_mode == 1)
//        {
//            $data["price"] = $this->getprice($user->id,$qwzs,$type);
//            //判断余额是否足够
//            if($user->score<=0){
//                $this->error("请确保您的积分余额充足!");
//            }
//            //判断余额至少需要当前价格的倍数
//            $price_times = config('site.price_times');
//            $need_score = $price_times * $data['price'];
//
//            if($user->score< $need_score){
//                $this->error("添加该关键字，积分余额必须大于".$need_score);
//            }
////
//        }

        if (request()->isPost()) {
            $name = input('post.name');
//            $type = input('post.type[]');
            $type = $_POST['type'];
//            var_dump($type);exit();
            $encodeName = urlencode($name);
            $url = "http://api.91cha.com/index?key=fa3ebdbc2dac4232add346c4b2171e56&kws=$encodeName";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            $result = curl_exec($ch);
            $data = json_decode($result, true);
            $value = $data['data'];
            foreach ($value as $k => $v) {
                $baiPc = $v['allindex'];
                $bai = $v['mobileindex'] . PHP_EOL;
                $so360 = $v['so360index'] . PHP_EOL;
                $so = round($v['mobileindex'] * 0.9) . PHP_EOL;
                $sm = round($v['mobileindex'] * 0.7);
//                array(5) {
//                [0]=> int(342)
//                [1]=> string(5) "215"
//                [2]=> string(4) "57"
//                [3]=> string(5) "194"
//                [4]=> float(151)

            }

            // 我根据你这句话的理解， 就是你给我一个$mypricelist，再给我一个 type  如果 typt=1 我告诉你 val5 => 15 有没有?

        }
//            halt($value);
        $group = [$baiPc, $bai, $so360, $so, $sm];
        foreach ($group as $k=>$v){

        }
//            var_dump($group);exit();
        $pricelist = model("UserGroup")->where('id', 1)->column('pricelist'); //默认的价格
        $allpricelist = model("UserGroup")->field('id,pricelist')->select(); //所有的价格
        $mypricelist = "";
        //取出该任务对应会员的价格区间
        $user = model('user')->where("id")->field('group_id,pricelist')->find();


        if (empty($user['pricelist']) || strlen($user['pricelist']) <= 2) {

            //匹配对应会员组的价格区间
            foreach ($allpricelist as $k => $v) {
                if ($user['group_id'] == $v['id']) {
                    $mypricelist = $v['pricelist'];
                    break;
                }
            }
            //无对应会员组采用默认的
            if (empty($mypricelist)) {
                $mypricelist = $pricelist[0];
            }
        } else {
            //该会员存在价格区间
            $mypricelist = $user['pricelist'];
        }

        //拿到价格区间之后开始计算对应价格。
        $mypricelist = json_decode($mypricelist, true);
        //计算价格
        $myprice = 0;

        foreach ($mypricelist as $kk => $vv) {

            //取出对应的价格
            if ($type == 1 || $type == 4) {
                // $vv["val5"] = $vv["baidu"];
            } else if ($type == 2 || $type == 5) {
                $vv["val5"] = $vv["sogou"];
            } else if ($type == 3 || $type == 6) {
                $vv["val5"] = $vv["qf360"];
            } else {
                $vv["val5"] = $vv["sm"];
            }
            //正常匹配指数
            if ($group >= $vv["val3"] && $group <= $vv["val4"]) {
                //匹配到了，分为正常价格和非正常价格

                if ($vv["val5"] < 1) {
                    $myprice = $group * floatval($vv["val5"]);
                    break;
                } else {
                    $myprice = floatval($vv["val5"]);
                    break;
                }
            }
            //匹配无穷大指数
            if ($group >= $vv["val3"] && $vv["val4"] == "-1") {
                //匹配到了，分为正常价格和非正常价格
                if ($vv["val5"] < 1) {
                    $myprice = $group * floatval($vv["val5"]);
                    break;
                } else {
                    $myprice = floatval($vv["val5"]);
                    break;
                }
            }


        }
//            halt($group);
//            echo $qwzs;

//            $user = $this->auth->getUser();
////            $user = (1);
//            $data['type']=$this->request->request('type');
//            $type = $data['type'];
//            $dat['price'] = $this->getprice($user->id,$group,$type);
//            var_dump($dat);exit();
//            $qwzs = $qwzs = czj_get_qwzs($this->request->request($encodeName));

        //指数模式： 计算关键字价格
//        $price_mode = config('site.price_mode');
//        if($price_mode == 1)
//        {
//            $data["price"] = $this->getprice($user->id,$group,$type);
        //判断余额是否足够
//            if($user->score<=0){
//                $this->error("请确保您的积分余额充足!");
//            }
        //判断余额至少需要当前价格的倍数
//            $price_times = config('site.price_times');
//            $need_score = $price_times * $data['price'];

//            if($user->score< $need_score){
//                $this->error("添加该关键字，积分余额必须大于".$need_score);
//            }
//
//        }




    }

    public function group()
    {
//        $a = 666;
        $a = [20,302];
        $res = [1];
        foreach($a as $k =>$v){
        //    里面写if条件
            $aa[] = Db::name('group')->where('val1','<=',$v)->where('val2','>=',$v)->select();

            $tot=count($res);
            for($i=0;$i<$tot;$i++)
            {
                if($res[$i]['bais']=='1')
                {
                    foreach($res[$i] as $a)
                    {
                        echo("<div>".$a."</div>");
                    }
                }
            }
//            foreach ($type as $k => $v){
//                $as[] = Db::name('group')->where('baipc','=',1)->where('bai','=',2)->select();
//            }
//            halt($as);
        }
        halt($aa);
        $type = 1;
        $l = Db::name('group')->where('id',$aa)->find();
        var_dump($l);
//        $ab = $aa['bai'];
//        var_dump($aa);
//        $v = $aaa[1];
//        $a11 = 309;
//        $aa=Db::name('group')->where('val2','>=',$a11)->find();
//        $b = 1;
//        $ab =$aa[];

//        $tt = $typeList;
//        var_dump($tt);
//        var_dump($aa);



// 把查询条件传入查询方法
//        $q = Db::name('group')->where($map)->select();
//        var_dump($q);
//        $a = 111;
//        if ($a >0 && $a<=100){
//            return 1;
//        }elseif ($a >101 && $a<=200){
//            return 2;
//        }elseif ($a >201 && $a<=300){
//
//        }elseif ($a >301 && $a<=400){
//
//        }elseif ($a >401 && $a<=500){
//
//        }
//        SELECT * FROM `co_group` WHERE (val1 < 100 and val2 >=100);
//        $q = Db::name('group')->where('val1','>=',$a)->where('val2','<=',$a)->select();
//        $q1 = Db::name('group')->where($map)->select();
//        halt($q);
    }

    public function add()
    {
        $a = 'si';
        $b = '301';
        $c = '350';
        $da =[
            'name'=>$a,
            'val1'=>$b,
            'val2'=>$c,
            'baipc'=> 9,
            'bai'=> 7,
            'sogou'=> 8,
            'so360'=> 6,
            'sm'=> 5,

        ];
        if (Db::name('group')->where('name',$a)->find())
        {
            return 'cunzai';
        }
        if (Db::name('group')->insert($da)){
            return 'ok';
        }else{
            return 'cuo';
        }
//        $a=[1,2];
//        $b=[3,4];
//        foreach($a as $k=>$v){
//            $bai = $v+1;
//            $b = $v+40;
//        }
//
//        $a = [$bai,$b];
//        halt($a);
//        foreach($b as &$value){
//            $value++;
//        }
//        print_r($a);
//        print_r($b);
    }

    public function server()
    {
//        $a = 111;
//        $c = round($a * 0.7);
//        var_dump($c);
//        if ($this->request->isPost()){//添加任务操作
//            $user = $this->auth->getUser();
//
//            $data['type']=$this->request->request("type");
//            $type=$data['type'];
//            $data['name']=trim($this->request->request("keyword"));
//            $data['url']=trim($this->request->request("url"));
//            $task_exist = $this->task_model->where($data)->find();
//            if($task_exist){
//                $this->error("该任务已存在，请勿重复添加。");
//            }
//            $qwzs = czj_get_qwzs($this->request->request("keyword"));
//            $data['tasktype']=$this->request->request("tasktype");
//            $data['qwzs']=$qwzs;
//            $data['user_id']=$user->id;
//            $data['urlmode']=$this->request->request("urlmode");
//            $data['createtime']=time();
//
//            //指数模式： 计算关键字价格
//            $price_mode = config('site.price_mode');
//            if($price_mode == 1)
//            {
//                $data["price"] = $this->getprice($user->id,$qwzs,$type);
//                //判断余额是否足够
//                if($user->score<=0){
//                    $this->error("请确保您的积分余额充足!");
//                }
//                //判断余额至少需要当前价格的倍数
//                $price_times = config('site.price_times');
//                $need_score = $price_times * $data['price'];
//
//                if($user->score< $need_score){
//                    $this->error("添加该关键字，积分余额必须大于".$need_score);
//                }
//
//            }
//
//            $this->task_model->insert($data);
//            $res['code']=1;
//            $res['msg']='添加成功';
//            $res['data']=$data;
//            $res['wait']=3;
//            $res['url']=url('user/index');
//            return json($res);
//            //$this->success("任务添加成功,请等待后台管理员审核 ","index/user/tasklist");
//        }
//        $this->view->assign('title', "添加任务");
//        $typeList= array (
//            '1' => '百度PC',
//            '2' => '搜狗PC',
//            '3' => '360PC',
//            '4' => '百度Wap',
//            '5' => '搜狗Wap',
//            '6' => '360Wap',
//            '7' => '神马搜索',
//        );
//        $this->view->assign('typeList', $typeList);
//        return $this->view->fetch();
    }

    //查询价格
    public function checkprice()
    {
        if ($this->request->isAjax())
        {
            $user=$this->auth->getUser();
            $group = czj_get_qwzs($this->request->request("keyword"));
            $type = $this->request->request("type");
            $price = $this->getprice($user->id,$group,$type);
            return json_encode(floatval(number_format($price,2)));
        }
    }



    //计算关键字价格 --- 指数模式
    protected function getprice($userid,$group,$type){

        $pricelist =  model("UserGroup")->where('id',1)->column('pricelist'); //默认的价格
        $allpricelist = model("UserGroup")->field('id,pricelist')->select(); //所有的价格

        $mypricelist="";
        //取出该任务对应会员的价格区间
        $user=  model("user")->where("id",$userid)->field('group_id,pricelist')->find();

        //该会员不存在价格区间，长度小于2也是不存在的
        if(empty($user['pricelist']) || strlen($user['pricelist'])<=2){

            //匹配对应会员组的价格区间
            foreach($allpricelist as $k=>$v){
                if($user['group_id']==$v['id']){
                    $mypricelist = $v['pricelist'];
                    break;
                }
            }
            //无对应会员组采用默认的
            if(empty($mypricelist)){
                $mypricelist = $pricelist[0];
            }
        }else{
            //该会员存在价格区间
            $mypricelist = $user['pricelist'];
        }

        //拿到价格区间之后开始计算对应价格。
        $mypricelist = json_decode($mypricelist,true);
        //计算价格
        $myprice = 0;

        foreach ($mypricelist as $kk => $vv) {

            //取出对应的价格
            if($type==1 || $type ==4){
                // $vv["val5"] = $vv["baidu"];
            }else if($type==2 || $type==5){
                $vv["val5"] = $vv["sogou"];
            }else if($type==3 || $type==6){
                $vv["val5"] = $vv["qf360"];
            }else{
                $vv["val5"] = $vv["sm"];
            }
            //正常匹配指数
            if($group >= $vv["val3"] && $group <= $vv["val4"])
            {
                //匹配到了，分为正常价格和非正常价格

                if($vv["val5"] <1)
                {
                    $myprice = $group * floatval($vv["val5"]);
                    break;
                }
                else
                {
                    $myprice = floatval($vv["val5"]);
                    break;
                }
            }
            //匹配无穷大指数
            if($group >= $vv["val3"] && $vv["val4"] == "-1")
            {
                //匹配到了，分为正常价格和非正常价格
                if($vv["val5"] <1)
                {
                    $myprice = $group * floatval($vv["val5"]);
                    break;
                }
                else
                {
                    $myprice = floatval($vv["val5"]);
                    break;
                }
            }


        }

        return $myprice;
    }

//    public function login()
//    {
//        if (request()->isPost()){
//            $name = input('name');
//            $pass = input('password');
//            $info = DB::name('admin')->where('name',$name)->find();
//            if(empty($info)){
////                $this->error('用户不存在，请重新登陆',url('/admin/login'));
//                return 'nameerror';
//            }else{
//                if(md5($pass)!=$info['password']){
////                    $this->error('密码不正确，请重新登陆',url('/admin/login'));
//                    return 'mimacuo';
//                }else{
////                    Session::set('name',$name);
////                    Session::set('id',$info["id"]);
////                    return show(200);
////                    return redirect('/admin');
////                    $this->success("登录成功！",url('/admin'));
//                    return 'ok';
//                }
//            }
//        }else{//如果不是post，则返回登陆界面
////            Session::clear();
////            return $this->fetch('login');
//            return 'error';
//
//        }
//    }

  function curl_request($url,$post='',$cookie='', $returnCookie=0){
          $curl = curl_init();
          curl_setopt($curl, CURLOPT_URL, $url);
          curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
          curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
          curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
          curl_setopt($curl, CURLOPT_REFERER, "http://www.baidu.com");
          if($post) {
              curl_setopt($curl, CURLOPT_POST, 1);
              curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
         }
         if($cookie) {
              curl_setopt($curl, CURLOPT_COOKIE, $cookie);
         }
         curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
         curl_setopt($curl, CURLOPT_TIMEOUT, 10);
         curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
         $data = curl_exec($curl);
         if (curl_errno($curl)) {
             return curl_error($curl);
         }
         curl_close($curl);
         if($returnCookie){
                     list($header, $body) = explode("\r\n\r\n", $data, 2);
             preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
             $info['cookie']  = substr($matches[1][0], 1);
             $info['content'] = $body;
             return $info;
         }else{
                     return $data;
         }
 }
}